<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option label="背景图" value="1" />
          <el-option label="轮播图" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="所属城镇" prop="category">
        <el-select v-model="queryParams.townCode" placeholder="请选择所属城镇" clearable size="small">
          <el-option
            v-for="city in cityList"
            :key="city.cityCode"
            :label="city.cityName"
            :value="city.cityCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属模块" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择所属大类" clearable size="small">
          <el-option
            v-for="sorts in sortsList"
            :key="sorts.sortCode"
            :label="sorts.sortName"
            :value="sorts.sortCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="有效开始时间" prop="startTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd HH:mm:dd"
          placeholder="选择有效开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效截至时间" prop="endTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd HH:mm:dd"
          placeholder="选择有效截至时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:banner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:banner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:banner:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:banner:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="图片地址" align="center" prop="bannerUrl" />-->
<!--      <div class="user-info-head"><img v-bind:src="options.img" title="点击上传头像" class="img-circle img-lg" /></div>-->
      <el-table-column label="类型" align="center" prop="type" />
<!--      <el-table-column label="跳转目标" align="center" prop="targetCode" />-->
      <el-table-column label="所属城镇" align="center" prop="townCode" />

      <el-table-column label="所属大类" align="center" prop="category" />
      <el-table-column label="banner图地址" align="center" prop="bannerUrl" :show-overflow-tooltip="true"/>
      <el-table-column prop="imgUrl" label="图片" align="center">
        <template slot-scope="scope">
            <div v-if="scope.row.bannerUrl !== null" class="wrap" align="left">
              <el-image
                v-for="(item,index) in scope.row.bannerUrl.split(',')"
                :key="index"
                :src="item" style="width:50px;height:30px;">
              </el-image>
            </div>
          </template>
      </el-table-column>
      <el-table-column label="有效开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效截至时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="是否删除" align="center" prop="deleteFlag" />-->
<!--      <el-table-column label="状态" align="center" prop="status" />-->
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdOn" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdOn, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateOn" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateOn, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:banner:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:banner:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

    <!-- 添加或修改bannan对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="type in typeList"
              :key="type.typeCode"
              :label="type.typeName"
              :value="type.typeCode">
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="跳转目标" prop="targetCode">-->
<!--          <el-input v-model="form.targetCode" placeholder="请输入跳转目标" />-->
<!--        </el-form-item>-->
        <el-form-item label="所属城镇" prop="townCode">
          <el-select v-model="form.townCode" placeholder="请选择所属城镇" clearable size="small">
            <el-option
              v-for="city in cityList"
              :key="city.cityCode"
              :label="city.cityName"
              :value="city.cityCode"/>
          </el-select>
        </el-form-item>
        <el-form-item label="所属大类" prop="category">
          <el-select v-model="form.category" placeholder="请选择所属大类" clearable size="small">
            <el-option
              v-for="sorts in sortsList"
              :key="sorts.sortCode"
              :label="sorts.sortName"
              :value="sorts.sortCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效开始时间" prop="startTime">
          <el-date-picker clearable size="small"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择有效开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效截至时间" prop="endTime">
          <el-date-picker clearable size="small"
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择有效截至时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="banner图" prop="showViews">
          <el-upload
            action="/application/banner/imageUpload"
            list-type="picture-card"
            accept="image/*"
            :limit="imgLimit"
            :file-list="productImgs"
            :multiple="isMultiple"
            :on-preview="handlePictureCardPreview"
            :before-upload="beforeAvatarUpload"
            :on-error="imgUploadError"
            :http-request="uploadSectionFile">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBanner, getBanner, delBanner, addBanner, updateBanner, exportBanner,sortList ,file_upload} from "@/api/application/banner/banner";

import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Banner",
  components: {
    ImageUpload
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      productImgs: [],
      isMultiple: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileList: [],
      // 非单个禁用
      single: true,
      urlMap: new Map(),
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // bannan表格数据
      bannerList: [],
      sortsList: [],
      typeList: [],
      cityList: [],
      excelListurl: [],
      urls: [],
      fileUploadList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        bannerUrl: null,
        type: null,
        targetCode: null,
        townCode: null,
        category: null,
        startTime: null,
        endTime: null,
        deleteFlag: null,
        status: null,
        createdBy: null,
        createdOn: null,
        updateOn: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "banner类型必输", trigger: "blur" }
        ],
        townCode: [
          { required: true, message: "banner所属城镇必输", trigger: "blur" }
        ],
        category: [
          { required: true, message: "banner所属模块必输", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCommonInfo();

  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          
        })
        .catch(_ => {});
    },
    uploadSectionFile(params) {
      const file = params.file;
      let param = new FormData(); //创建form对象
      param.append('file', file); //通过append向form对象添加数据
      file_upload(param).then(response => {
        this.fileUploadList.push(response.url);
        this.form.bannerUrl = this.fileUploadList.join(",");
      })
    },
    // handleRemove(file, fileList) {//移除图片
    //   console.log(file, fileList);
    // },

    handlePictureCardPreview(file) {//预览图片时调用
      this.fileUploadList.forEach(url =>{
        console.log(file);
        this.dialogImageUrl = url;
        this.dialogVisible = true;
      })
    },
    beforeAvatarUpload(file) {//文件上传之前调用做一些拦截限制
      console.log(file);
      const isJPG = true;
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      // this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    handleExceed(files, fileList) {//图片上传超过数量限制
      this.$message.error('上传图片不能超过6张!');
      console.log(file, fileList);
    },
    imgUploadError(err, file, fileList) {//图片上传失败调用
      console.log(err)
      this.$message.error('上传图片失败!');
    },

    /*获取全局信息*/
    getCommonInfo() {
      this.loading = true;
      sortList().then(response => {
        this.sortsList = response.data.sortInfoBos;
        this.typeList = [{typeCode: 1,typeName: "背景图"},{typeCode: 2,typeName: "轮播图"}];
        this.cityList = response.data.cityVo;
        this.loading = false;
      });
    },
    /** 查询bannan列表 */
    getList() {
      this.loading = true;
      listBanner(this.queryParams).then(response => {
        this.bannerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        bannerUrl: null,
        type: null,
        targetCode: null,
        townCode: null,
        category: null,
        startTime: null,
        endTime: null,
        deleteFlag: null,
        status: 0,
        createdBy: null,
        createdOn: null,
        updateBy: null,
        updateOn: null
      };
      this.productImgs=null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加bannan";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBanner(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改bannan";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          for(let value of this.urlMap.values()){
            this.fileUploadList.push(value);
          }
          this.form.files = this.fileUploadList;
          if (this.form.id != null) {
            updateBanner(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBanner(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除bannan编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBanner(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有bannan数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBanner(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
